import json
from .settings import JSON_FILEPATH
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import sys

sys.path.append('..')
import database


@require_http_methods(["GET"])
def test(request):
    return JsonResponse({'res': "Hello world ! "})


@require_http_methods(["GET"])
def getswitchinfo(request):
    response = {}
    try:
        file = open(JSON_FILEPATH + '/switchInfo.json')
        response = json.load(file)
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0
    return JsonResponse(response)


@require_http_methods(["GET"])
def getprotocolinfo(request):
    response = {}
    try:
        file = open(JSON_FILEPATH + '/protocolInfo.json')
        response = json.load(file)
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0
    return JsonResponse(response)


@require_http_methods(["GET"])
def getatinfo(request):
    response = {}
    try:
        file = open(JSON_FILEPATH + '/atInfo.json')
        response = json.load(file)
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0
    return JsonResponse(response)


@require_http_methods(["GET"])
def getchartdata(request):
    response = {}
    try:
        chart_file = open(JSON_FILEPATH + '/chartData.json')
        ava_file = open(JSON_FILEPATH + '/Availability.json')
        err_file = open(JSON_FILEPATH + '/ErrPercent.json')
        response = {
            'chart_json': json.load(chart_file),
            'ava_json': json.load(ava_file),
            'err_json': json.load(err_file)
        }
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0
    return JsonResponse(response)


@require_http_methods(["GET"])
def getHistoricalPortData(request):
    response = {}
    try:
        port = request.GET.get('port')
        startTime = request.GET.get('startTime')
        endTime = request.GET.get('endTime')

        result = database.queryPort(startTime, endTime, port)
        response = {
            'chart': result[0],
            'table': result[1]
        }
        print(response['table'])
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0

    return JsonResponse(response)


@require_http_methods(["GET"])
def getHistoricalProtocolData(request):
    response = {}
    try:
        startTime = request.GET.get('startTime')
        endTime = request.GET.get('endTime')
        result = database.queryShare(startTime, endTime)
        response = {
            'chart': result[0],
            'table': result[1]
        }
        print(response)
    except Exception as e:
        response['msg'] = str(e)
        response['ok'] = 0
    return JsonResponse(response)
